
### V table 4 : table A8 :  procedure analysis :  -------------------------------------------

get_table_4 <- function( con,
                         data_adm= dt_adm[max_cost_row == 1 ]
                         ) {
  admissions <- tbl(con, dbplyr::in_schema("temp_sample_cancer_admissions_encoded")) %>%
    mutate(zihui_bikur = as.character(zihui_ishpuz_bikur)) %>% 
    collect() %>% 
    data.table()
  
  
  dt_admissions<- merge(x = data_adm[,.(zihui_bikur,id_var)], 
                      y = admissions , 
                      by = c("zihui_bikur","id_var"),
                      all.x = T,
                      all.y = F
  )
  
  names(admissions)
  return(dt_admissions %>% filter( !is.na(zihui_ishpuz_bikur) ) )
}



do_table_4<-function( drop_cols = c("id_var"  ,"zihui_bikur",  "zihui_ishpuz_bikur" ) ) { 
  
  admissions <- get_table_4() %>%  select(-drop_cols)
  ### All Admissions:
  proce_all<- 
    admissions %>%
    group_by(group) %>%
    add_tally %>%
    summarise_all(mean, na.rm=T) %>%
    select(group:Other, n) %>%
    ungroup() %>%
    list() %>%
    map2(.x=., .y=list(admissions %>% add_tally()) ,
         .f= ~bind_rows(.x, summarise_at(.y, 1:6, mean, na.rm=T) %>% 
                          mutate(group='All') %>%
                          mutate(n = mean(.y$n)))) %>%
    .[[1]] %>%
    mutate_at(2:7, funs(round(., 3))) %>%
    rename('Time Before Death' = group, 'N of Admissions' = n)
  
  proce_all <- proce_all  %>% 
    rename(Maintenance = Maintanance) %>%
    mutate_at( vars(Maintenance:Other), funs( format(round(.*100,1) ,nsmall = 1 ) )) %>%
    mutate (`N of Admissions` = scales::comma(`N of Admissions`) )
  
  proce_all[1,]$`Time Before Death`<- "Last month"
  
  invisible(Hmisc::latex(
    proce_all[,-1],
    file = paste0("proc_by_time_before_death.tex"),
    center = 'centering',
    n.cgroup = c(6,1 ),
    cgroup   = c("Procedure Type, Admission With Any (\\%)",""),
    rowname =proce_all$`Time Before Death`,
    rowlabel = "",
    col.just = c("l", rep.int("r", 7)),
    extracolheads = c("(1)", "(2)", "(3)", "(4)","(5)","(6)","(7)"), 
    extracolsize = "normalsize"
  ))
  proce_all
}


















